<template>
	<div class="container">
		<el-table
			border
			:data="tableData"
			:header-cell-style="getRowClass"
			header-align="center"
			style="width: 100%;"
			highlight-current-row
		>
			<el-table-column
				:label="`${$t('dxn.card_ables_list.detail_rules')}`"
				min-width="100"
				align="center"
			>
				<template slot-scope="scope">
					<el-button
						type="primary"
						:loading="ruleLoading"
						@click="handleDetailRules(scope.row)"
					>
						{{ $t('dxn.card_ables_list.view_rules') }}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column label="保险信息" min-width="100" align="center">
				<template slot-scope="scope">
					<span
						class="text-link"
						@click="
							$router.push({
								path: '/dxn/insureManager/insureList',
								query: {
									tableId: scope.row.tableCode
								}
							})
						"
					>
						保险详情
					</span>
				</template>
			</el-table-column>
			<el-table-column
				:label="`${$t('dxn.card_ables_list.operate')}`"
				min-width="100"
				align="center"
			>
				<template slot-scope="scope">
					<el-button
						type="danger"
						:loading="dissLoading"
						@click="handleDissolution(scope.row)"
					>
						{{ $t('dxn.card_ables_list.dissolution') }}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column
				min-width="100"
				align="center"
				:label="`${$t('dxn.card_ables_list.set_robots_number')}`"
			>
				<template slot-scope="{ row }">
					<template v-if="edit">
						<el-input
							v-model="robotNum"
							:placeholder="
								`${$t(
									'dxn.card_ables_list.set_robots_number_placeholder'
								)}`
							"
							size="small"
							:min="0"
							:max="maxRobotNum"
							:precision="0"
							:step="1"
							step-strictly
							:controls="false"
							v-input="{ name: 'int' }"
							@input="onRobotNumInput"
						/>
						<el-button
							class="cancel-btn"
							size="small"
							icon="el-icon-refresh"
							type="warning"
							@click="cancelEdit(row)"
						>
							{{ $t('dxn.card_ables_list.cancel') }}
						</el-button>
					</template>
					<span v-else>{{ robotNum }}</span>
				</template>
			</el-table-column>

			<el-table-column
				align="center"
				:label="`${$t('dxn.card_ables_list.operate')}`"
				width="150"
			>
				<template slot-scope="{ row }">
					<el-button
						v-if="edit"
						type="success"
						size="small"
						icon="el-icon-circle-check-outline"
						:loading="robotLoaing"
						@click="confirmEdit(row)"
					>
						{{ $t('dxn.card_ables_list.confirm') }}
					</el-button>
					<el-button
						v-else
						type="primary"
						size="small"
						icon="el-icon-edit"
						@click="edit = !edit"
					>
						{{ $t('dxn.card_ables_list.edit_robot_num') }}
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<RuleDialog
			:visible.sync="showRuleDialog"
			:detail="ruleDetail"
			:bbSettingLabel="bbSettingLabel"
			:unitLabel="unitLabel"
		/>
	</div>
</template>

<script>
import RuleDialog from '../RuleDialog'
import list from '@/mixins/list'
import { Decimal } from 'decimal.js'
import {
	insuranceModeMap,
	serviceChargeTypeArr,
	squidRewardModelArr
} from '@/dict/dxn'
export default {
	components: {
		RuleDialog
	},
	mixins: [list],
	props: {
		queryData: {
			type: Object,
			default: () => {}
		},
		gameTypeId: {
			require: true,
			type: Number,
			default: null
		},
		detailTableId: {
			require: true,
			type: Number,
			default: null
		},
		tableData: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			showRuleDialog: false,
			ruleDetail: {},
			dissLoading: false,
			robotNum: null,
			edit: false,
			robotLoaing: false,
			ruleLoading: false,
			bbSettingLabel: '',
			unitLabel: '',
			unitName: '',
			maxSeats: 0,
			maxRobotNum: 8, // 最大机器人数量
			insuranceModeMap,
			serviceChargeTypeArr,
			squidRewardModelArr
		}
	},
	watch: {
		tableData(val) {
			if (Array.isArray(val) && val.length) {
				this.robotNum = val[0].robotNum
				// maxSeats牌桌最大人数，暂时用不上
				// this.maxSeats = val[0].maxSeats
			}
		}
	},
	created() {},
	methods: {
		// 输入值校验
		onRobotNumInput(val) {
			if (!val) {
				this.robotNum = 0
			}
			if (val > this.maxRobotNum) {
				this.robotNum = this.maxRobotNum
			}
		},
		cancelEdit() {
			this.edit = false
			if (Array.isArray(this.tableData) && this.tableData.length) {
				this.robotNum = this.tableData[0].robotNum
			}
		},
		// 编辑机器人数量
		confirmEdit() {
			this.edit = true
			this.robotLoaing = true
			this.$api
				.updateRobotNumBend({
					id: this.detailTableId,
					robotNum: this.robotNum
				})
				.then((res) => {
					this.$message.success(this.$t('common.action_success'))
					this.$emit('updateRobotNum')
				})
				.catch(() => {})
				.finally(() => {
					this.robotLoaing = false
					this.edit = false
				})
		},
		getRowClass({ row, column, rowIndex, columnIndex }) {
			if (rowIndex === 0) {
				return 'background:#EFEFEF'
			} else {
				return ''
			}
		},
		// 解散
		async handleDissolution(val) {
			this.dissLoading = true
			try {
				const dissolveResult = await this.$api.getCardTableDissolveJudgeBend(
					{ id: this.detailTableId }
				)
				this.dissLoading = false

				if (dissolveResult?.code !== 200) {
					return
				}
				// 70001: 当前牌局没有进行中的手牌（包括牌局未开始，以及当前不满足自动开桌人数）
				// 70002: 当前牌局有进行中的手牌（非鱿鱼模式）;若当前牌局有进行中的手牌（鱿鱼模式-非鱿鱼轮次）
				// 70003: 当前牌局有进行中的手牌（鱿鱼模式-鱿鱼轮次）
				const confirmContentMap = new Map([
					[70001, '确定解散牌桌？'],
					[
						70002,
						'当前有手牌正在进行中，确定强制解散牌桌？强制解散后本手牌直接结束，所有人本手牌下注退回，此手牌作为异常局，没有输赢和抽水'
					],
					[
						70003,
						'当前处于鱿鱼游戏中，确定强制解散牌桌？强制解散后本手牌直接结束，所有人本手牌下注退回，此手牌作为异常局，没有输赢和抽水，此轮鱿鱼游戏不结算'
					]
				])

				this.$confirm(
					confirmContentMap.get(dissolveResult?.data) ||
						'确定解散牌桌吗？',
					this.$t('dxn.card_ables_list.prompt'),
					{
						confirmButtonText: this.$t(
							'dxn.card_ables_list.confirmButtonText'
						),
						cancelButtonText: this.$t(
							'dxn.card_ables_list.cancelButtonText'
						),
						type: 'warning'
					}
				)
					.then(() => {
						this.dissLoading = true
						this.$api
							.dxtableGameDissolveBend({ id: this.detailTableId })
							.then(() => {
								this.$message({
									type: 'success',
									message: this.$t(
										'dxn.card_ables_list.dissolve_success'
									)
								})
								this.$emit('dissolve')
							})
							.catch(() => {})
							.finally(() => {
								this.dissLoading = false
							})
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: this.$t('dxn.card_ables_list.canceled')
						})
					})
			} catch (err) {
				this.dissLoading = false
			}
		},
		// 查看规则
		handleDetailRules() {
			const texasGameTypeIdArr = [1, 3] // 德州和aof德州
			const shortGameTypeIdArr = [2, 4] // 短牌和aof短牌
			if (texasGameTypeIdArr.includes(this.gameTypeId)) {
				this.bbSettingLabel = this.$t('dxn.game_rule.bb')
				this.unitLabel = this.$t('dxn.game_rule.bb_unit')
				this.unitName = this.$t('dxn.game_rule.insure_trigger_bb')
			} else if (shortGameTypeIdArr.includes(this.gameTypeId)) {
				this.bbSettingLabel = this.$t('dxn.game_rule.ante')
				this.unitLabel = this.$t('dxn.game_rule.ante_unit')
				this.unitName = this.$t('dxn.game_rule.insure_trigger_ante')
			}
			this.ruleDetail = {}
			this.showRuleDialog = true
			this.ruleLoading = true
			this.$api
				.getDxtableDetailBend({
					id: this.detailTableId
				})
				.then((res) => {
					const data = res.data
					let bbDefaultCarry = data.bringChipTimes
					// bringChipTimes没有值，则做相除获取
					if (!bbDefaultCarry) {
						if (parseFloat(data.bbBlindScore) > 0) {
							bbDefaultCarry =
								parseFloat(data.bringChipScore) /
								parseFloat(data.bbBlindScore)
						} else {
							bbDefaultCarry = data.bringChipScore
						}
					}
					this.ruleDetail = {
						tableType: data.tableType,
						// gameName: data.gameTypeName,
						gameName: this.typeFilter(data.tableType, 'gameType'),
						status: data.status,
						gameOvertime: data.gameOvertime,
						bbSetting: data.bbBlindScore,
						bbDefaultCarry: bbDefaultCarry, // data.bringChipScore
						complementLowerLimit: data.minBringChipScore,
						complementUpperLimit: data.maxBringChipScore,
						gameTimes:
							Math.round((data.timeCount / 60) * 100) / 100, // 分钟转换为小时
						gamePeopleNumbers: data.maxSeats || 0,
						autoStartNumbers: data.autoStartUserCounts,
						// rake: data.rake * 100,
						insuranceIsShow: data.insuranceMode !== null,
						isEVInsurance: data.insuranceMode == 2, // 2为EV保险
						insuranceMode: data.insuranceMode,
						insuranceModeStr: data.insuranceModeStr,
						insuranceTurn: data.insuranceTurn + '%底池',
						insuranceLowerLimit:
							data.insuranceLowerLimit + this.unitLabel, // 保险触发下限
						anteSwitch: data.anteSwitch, // 前注功能 0-关闭 1-开启 2-关闭隐藏
						anteLimit: data.anteLimit + this.unitLabel, // 前注倍数
						anteScore: data.anteScore, // 前注倍数乘以大盲
						showOutsWinn: data.showOutsWinn, // ALLIN展示OUTS与胜率 0-关闭 1-开启 2-关闭隐藏
						isActiveTakeout: data.isActiveTakeout, // 允许主动带出0-关闭 1-开启  2-关闭隐藏
						needKeepChips:
							(data.needKeepChips || 0) + this.unitLabel, // 必要保留筹码
						serviceChargeType: data.serviceChargeType,
						serviceChargeTypeName: this.getTypeName(
							data.serviceChargeType,
							this.serviceChargeTypeArr
						), // 每手服务费: 1: 底池比例,2: 盈利比例
						chargeScale: (data.gameRake || 0) + '%', // 收费比例
						handChargeUpperLimit: data.handChargeUpperLimit || 0, // 每手收费上限
						isHiddenDecimal: data.isHiddenDecimal, // 隐藏小数开关 0-关闭 1-开启  2-关闭隐藏
						preflopDelay: data.preflopDelay || 0, // 0-配置没开启  1-关 2-开 默认为0
						voiceChatSwitch: data.voiceChatSwitch || 0, // 语音聊天功能 0-关闭 1-开启 2-关闭隐藏
						onlyDirectMemberSwitch:
							data.onlyDirectMemberSwitch || 0, // 仅限直属会员可见 0-隐藏 1-展示
						onlyDirectMember: data.onlyDirectMember || 0, //  0-关闭 1-开启
						tableEntryPasswordSwitch:
							data.tableEntryPasswordSwitch || 0, // 入桌密码功能 0-关闭 1-开启 2-关闭隐藏
						tableEntryPassword: data.tableEntryPassword, // 入桌密码
						tableFeeSwitch: data.tableFeeSwitch || 0, // 局服务开关 0-配置没开启  1-关 2-开
						tableFee: data.tableFee, // 局服务费
						tableFeeScale: data.tableFeeScale
							? data.tableFeeScale + '%'
							: '', // 局服务费比例
						multiPoolSwitch: data.multiPoolSwitch, // 多池购保 0-配置没开启  1-关 2-开
						drawLotsSeatingSwitch: data.drawLotsSeatingSwitch, // 抽签入座 0-默认（没有配置） 1-关闭，2-开启
						singleActionDelaysNumber:
							data.singleActionDelaysNumber || 0, // 单次行动延时次数
						forceOutSwitch: data.forceOutSwitch || 0, // 强制带出 0-默认（没有配置） 1-关闭，2-开启
						forceComplementSwitch: data.forceComplementSwitch || 0, // 强制补码 0-默认（没有配置） 1-关闭，2-开启
						forceOutBb: data.forceOutBb + this.unitName, // 强制带出大盲
						forceComplementBb:
							data.forceComplementBb + this.unitName, // 强制补码大盲
						halfDiscountSwitch: data.halfDiscountSwitch || 0, // 低于三人五折 0-默认（没有配置） 1-关闭，2-开启
						straddleSwitch: data.straddleSwitch || 0, // 强抓开关 0-默认（没有配置） 1-关闭，2-开启
						realTimeVoiceSwitch: data.realTimeVoiceSwitch || 0, // 实时语音 0-默认（没有配置） 1-关闭，2-开启
						realTimeVideoSwitch: data.realTimeVideoSwitch || 0, // 实时视频 0-默认（没有配置） 1-关闭，2-开启
						bottomPoolPeopleMaximum: data.bottomPoolPeopleMaximum, // 底池人数上限
						gpsImposeSwitch: data.gpsImposeSwitch || 0, // GPS限制 0-默认（没有配置） 1-关闭，2-开启
						ipImposeSwitch: data.ipImposeSwitch || 0, // IP限制 0-默认（没有配置） 1-关闭，2-开启
						onlyIosDeviceSwitch: data.onlyIosDeviceSwitch || 0, // 仅IOS设备限制 0-默认（没有配置） 1-关闭，2-开启
						riverInsuranceSplitOutsSwitch:
							data.riverInsuranceSplitOutsSwitch || 0, // River保险可买平分Outs 0-默认（没有配置） 1-关闭，2-开启
						paySeePastHandSwitch: data.paySeePastHandSwitch || 0, // 付费看以往手牌
						preflopEndFreeSwitch: data.preflopEndFreeSwitch || 0, // PreFlop结束免费
						singleBottomPoolLeaderLimit:
							data.singleBottomPoolLeaderLimit || 0 // 单底池领先人数上限
					}
					// 鱿鱼配置数据处理
					this.ruleDetail.squidGameSwitch = data.squidGameSwitch || 0 // 鱿鱼游戏开关 0-默认（没有配置） 1-关闭，2-开启
					if (this.ruleDetail.squidGameSwitch === 1) {
						this.ruleDetail.rewardModelName = '关闭'
					} else if (this.ruleDetail.squidGameSwitch === 2) {
						this.ruleDetail.rewardModel = data.rewardModel
						this.ruleDetail.rewardModelName = this.getTypeName(
							data.rewardModel,
							this.squidRewardModelArr
						) // 鱿鱼奖励模式
						this.ruleDetail.rewardValue =
							data.squidRewardValue + this.unitLabel // 奖励值(倍BB)
						this.ruleDetail.rewardValueCal =
							'即 ' + data.squidRewardPrice
						this.ruleDetail.minimumPeopleNumber =
							data.minimumPeopleNumber // 最低人数
						this.ruleDetail.maximumRound =
							Number(data.maximumRound) === -1
								? '无限'
								: data.maximumRound // 最大轮次
						this.ruleDetail.squidUpperLimit =
							Number(data.squidUpperLimit) === -1
								? '无限'
								: data.squidUpperLimit // 鱿鱼上限
						this.ruleDetail.triggerModeName =
							Number(data.triggerMode) === 0
								? '无限'
								: data.handTriggerNumber // 触发方式
						this.ruleDetail.mostSquidWinsSwitch =
							data.mostSquidWinsSwitch || 0 // 鱿鱼最多者独赢开关 0-默认（没有配置） 1-关闭，2-开启
						this.ruleDetail.capotSquidNumberLowerLimit =
							data.capotSquidNumberLowerLimit || 0 // 独赢鱿鱼数下限
						this.ruleDetail.multipleRewardSwitch =
							data.multipleRewardSwitch || 0 // 多重奖励开关 0-默认（没有配置） 1-关闭，2-开启
						this.ruleDetail.noActionWinsNoSquidSwitch =
							data.noActionWinsNoSquidSwitch || 0 // 无动作获胜无鱿鱼开关 0-默认（没有配置） 1-关闭，2-开启
						this.ruleDetail.firstSquidForceFlashSwitch =
							data.firstSquidForceFlashSwitch || 0 // 首次获得鱿鱼强制亮牌开关 0-默认（没有配置） 1-关闭，2-开启
					}
					// 前注计算乘以大盲
					if (data.anteSwitch === 1) {
						this.ruleDetail.anteScoreCal =
							'即 ' + Number(data.anteScore || 0)
					} else {
						this.ruleDetail.anteScoreCal = 0
					}
					// 0: 不开保险, 1: 经典保险
					this.ruleDetail.insuranceModeStr =
						this.insuranceModeMap[data.insuranceMode] ||
						data.insuranceModeStr
					// 计算必要保留筹码
					this.ruleDetail.needKeepChipsCal =
						'即 ' +
						Number(
							Decimal.mul(
								data.needKeepChips || 0,
								data.bbBlindScore || 0
							).toFixed(2, Decimal.ROUND_DOWN)
						)

					// 计算保险触发下限
					this.ruleDetail.insuranceLowerLimitCal =
						'即 ' +
						Number(
							Decimal.mul(
								data.insuranceLowerLimit || 0,
								data.bbBlindScore || 0
							).toFixed(2, Decimal.ROUND_DOWN)
						)
					// 计算EV提取下限
					this.ruleDetail.evExtractionLowerLimit =
						Number(
							Decimal.div(
								data.evExtractionLowerLimit || 0,
								data.bbBlindScore
							).toFixed(2, Decimal.ROUND_DOWN)
						) + this.unitLabel // EV提取下限(倍BB)

					this.ruleDetail.evExtractionLowerLimitCal =
						'即 ' + data.evExtractionLowerLimit

					// 计算每手收费上限
					if (data.handChargeUpperLimit === 0) {
						this.ruleDetail.handChargeUpperLimit = '无上限'
						this.ruleDetail.handChargeUpperLimitCal = 0
					} else {
						this.ruleDetail.handChargeUpperLimit += this.unitLabel
						this.ruleDetail.handChargeUpperLimitCal =
							'即 ' +
							Number(
								Decimal.mul(
									data.handChargeUpperLimit || 0,
									data.bbBlindScore || 0
								).toFixed(2, Decimal.ROUND_DOWN)
							)
					}
					// 判断盲注data.bbBlindScore或前注data.anteSwitch：1，data.anteLimit是否包含小数
					if (data.anteSwitch === 1) {
						this.ruleDetail.isShowHiddenDecimal =
							data.bbBlindScore % 1 === 0 &&
							data.anteLimit % 1 === 0
					} else {
						this.ruleDetail.isShowHiddenDecimal =
							data.bbBlindScore % 1 === 0
					}
				})
				.catch(() => {})
				.finally(() => {
					this.ruleLoading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.edit-input {
	padding-right: 100px;
}
.cancel-btn {
	position: absolute;
	right: 15px;
	top: 20px;
}
</style>
